require('../css/course.less');
// 接口请求
const BASE_URL = 'http://139.9.177.51:8099';
document.ready(function () {
    window.utils.addTabs(1);
    //判断用户是否登录,没登录跳转到登录
    window.utils.checkUserLogin();

    // 获取id
    const userId = JSON.parse(window.localStorage.getItem('user')).user.userId;
    console.log(userId);

    // 缓存 DOM 节点
    const latestCourseWrapper = document.querySelector('#latestCourseWrapper');
    const latestImg = document.querySelector('#latestImg');
    const latestTitle = document.querySelector('#latestTitle');
    const latestDesc = document.querySelector('#latestDesc');
    const courseList = document.querySelector('#courseList');
    // 给当前用户保存课程
    $http.post('/sports/saveCourse', {
        userId,
        courseIds: [3, 4, 5, 6, 7]
    }, function (res) {
        if (res.status === 0) {
            // 获取训练课程列表
            $http.get(`/sports/courseList?id=${userId}`, function (res) {
                if (res.status === 0) {
                    console.log(res);
                    const latestCourseData = res.data.filter(function (item) {
                        return item.latest === 1;
                    })[0];
                    // 渲染最新课程
                    latestCourseWrapper.href = `./course-detail.html?id=${latestCourseData.courseId}`;
                    latestImg.src = `${BASE_URL}${latestCourseData.imgurl}`;
                    latestTitle.textContent = latestCourseData.name;
                    latestDesc.textContent = latestCourseData.desc;

                    // 课程列表数据
                    const courseListData = res.data.filter(function (item) {
                        return item !== null && item.latest === 0;
                    })
                    let html = '';
                    courseListData.forEach(function (item) {
                        // 拼接
                        html += `
                    <a class="course-wrapper" href="./course-detail.html?id=${item.courseId}">
                        <img class="course-img" src="${BASE_URL}${item.imgurl}">
                        <h3>${item.name}</h3>
                        <p>${item.desc}</p>
                    </a>
                `
                    });
                    courseList.innerHTML = html;
                }
            })
        }
    })
})